package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private final String name;

    private final StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec 锁的过期时间，单位秒
     * @return 是否获取成功
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //1.获取当前线程的id
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //2.获取锁的key
        //3.写入redis
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unLock() {
        //1.获取当前线程的id
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //2.获取锁的key
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX+name);
        //3.释放锁之前判断锁是否属于当前线程，防止误删锁
        if (threadId.equals(id)){
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }
    }
}
